package com.peoit.honeycomb.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * 上传工具
 * Created by wxzhou on 2015/10/16.
 */
public class UploadUtil2 {
    //上传文件根路径
    public static final String DEFAULT_UPLOAD_PATH = PropertiesIn.upload;

    public static final String URL_SEPARATOR = File.separator;

    /**
     * 获取上传路径
     *
     * @return
     */
    public static String getDefaultUploadPath() {
        return DEFAULT_UPLOAD_PATH;
    }

    /**
     * 上传文件名+上传路径图
     *
     * @param fileName
     * @return
     */
    public String getWithDefaultPath(String fileName,HttpServletRequest request) {
        //取得根目录路径
        String path5 = System.getProperty("user.dir");
        String path = this.getClass().getClassLoader().getResource("").getPath();

        return path5+URL_SEPARATOR+DEFAULT_UPLOAD_PATH + URL_SEPARATOR + fileName;
    }

    /**
     * 得到相对路径
     * @param fileName
     * @return
     */
    public String getRelative(String fileName) {
        return URL_SEPARATOR+DEFAULT_UPLOAD_PATH + URL_SEPARATOR + fileName;
    }

    /**
     * 获取当前上传目录
     * @return
     */
    public String getPathse() {
        //取得根目录路径
//        String path = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        String property = System.getProperty("user.dir");
        String path5 = property;
        return path5+URL_SEPARATOR+DEFAULT_UPLOAD_PATH + URL_SEPARATOR ;
    }


    public static String uploadFile(HttpServletRequest request ,InputStream inputStream,String oldFileName) {
        return uploadFile(request ,inputStream, oldFileName, null);
    }

    /**
     * 上传文件
     * @param inputStream
     * @param oldFileName
     * @param fileName
     * @return
     */
    public static String uploadFile(HttpServletRequest request ,InputStream inputStream,String oldFileName,  String fileName) {
        //判断文件名是否有路径。如果有，则创建
        String withDefaultPath = null;
        String relativePath = "";
        try {
            fileName = getFileName(oldFileName, fileName);
            UploadUtil2 uploadUtil = new UploadUtil2();
            withDefaultPath = uploadUtil.getWithDefaultPath(fileName,request);
//            isExist(withDefaultPath);

            File dirFile = new File(uploadUtil.getPathse());
            if (!dirFile.exists()) {
                dirFile.mkdir();
                System.out.println("创建目录为：" + dirFile);
            }
            relativePath = uploadUtil.getRelative(fileName);
            FileOutputStream fos = new FileOutputStream(withDefaultPath);
            try {
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    fos.write(bytes, 0, read);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                fos.flush();
                fos.close();
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return relativePath;
    }

    public static  String getFileName(String oldFileName, String fileName){
        if(!StringUtils.isEmpty(fileName)) return fileName;
        fileName = getRandomFileName() + "." + getExtensionName(oldFileName);
        return fileName;
    }

    /**
     * 获取文件全路径
     *
     * @param fileName
     * @return 返回文件物理路径
     */
    public static String getFileFullPath(String fileName) {
        return getDefaultUploadPath() + System.getProperty("file.separator") + fileName;
    }

    /**
     * 获取一个随机生成的文件名，不带后缀
     *
     * @return
     */
    public static String getRandomFileName() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 获取不带扩展名的文件名
     *
     * @param filename
     * @return
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 获得UniqId
     */
    public static String getId() {
        String id = UUID.randomUUID().toString();
        id = id.replaceAll("-", "");
        return id;
    }

}
